/*
 * Copyright 2012-2013 EZC Group S.A. RCS Luxembourg B140949
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.yobidrive.y3.v1.client.http.handlers;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;

import com.yobidrive.y3.http.HttpResponseHandler;
import com.yobidrive.y3.v1.model.LeafContentMetadata;


public class GetLeafContentMetadataAndStreamResponseHandler extends HttpResponseHandler<LeafContentMetadata>{

	static private final Logger logger = Logger.getLogger(GetLeafContentMetadataAndStreamResponseHandler.class);

	private OutputStream destinationStream;
	
	public GetLeafContentMetadataAndStreamResponseHandler(OutputStream destinationStream) {
		super();
		this.destinationStream = destinationStream;
	}

	@Override
	/**
	 * Recover the stream of the response
	 * Never returns anything but null
	 */
	public LeafContentMetadata handleResponse(HttpResponse response)
			throws ClientProtocolException, IOException {
		
		//Call super to handle every error messages
		super.handleResponse(response);
		
		LeafContentMetadata result = new LeafContentMetadata();
		
		//Parse XML response if a stream is present
		if ( destinationStream != null ) {
			HttpEntity entity = response.getEntity();
			if ( entity != null ) { 
				result.contentLength = (int)entity.getContentLength();
				InputStream in = entity.getContent();
				byte[] buf = new byte[1024 * 16 ];
				int len; 
				while ((len = in.read(buf)) > 0){
					destinationStream.write(buf, 0, len);
				}
			} 
		} else {
			try { result.contentLength = Integer.parseInt(response.getFirstHeader("Content-Length").getValue()); }
			catch (Exception ex) { logger.warn("Unable to recover Content-Lengthfrom response",ex); }
		}

		try { result.contentType	= response.getFirstHeader("Content-Type").getValue(); }
		catch (Exception ex) { logger.warn("Unable to recover Content-Type from response",ex); }
		
		try { result.contentMD5	= response.getFirstHeader("Content-MD5").getValue(); }
		catch (Exception ex) { logger.warn("Unable to recover Content-MD5 from response"); }
		
		return result; //Nothing to return
	}
	
	
}
